package com.ysd.lis.service.samsto.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.dto.samsto.SamstoStorageDto;
import com.ysd.lis.dto.samsto.SamstoStorageFridgeDto;
import com.ysd.lis.dto.samsto.StorageDto;
import com.ysd.lis.entity.SysOrgDepartment;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.samsto.SamstoFridge;
import com.ysd.lis.entity.samsto.SamstoStorage;
import com.ysd.lis.mapper.samsto.SamstoStorageFridgeMapper;
import com.ysd.lis.mapper.samsto.SamstoStorageMapper;
import com.ysd.lis.request.samsto.SamstoStorageParam;
import com.ysd.lis.service.samsto.SamstoStorageService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 样本仓库表(SamstoStorage)表服务实现类
 *
 * @author leiming
 * @since 2024-10-25 14:33:38
 */
@Service("samstoStorageService")
public class SamstoStorageServiceImpl extends ServiceImpl<SamstoStorageMapper, SamstoStorage> implements SamstoStorageService {

    @Autowired
    private SamstoStorageFridgeMapper storageFridgeMapper;

    private MPJLambdaWrapper<SamstoStorage> initWrapper() {
        MPJLambdaWrapper<SamstoStorage> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        //ID
        lambdaQueryWrapper.selectAs(SamstoStorage::getId, SamstoStorage::getId);
        //名称
        lambdaQueryWrapper.selectAs(SamstoStorage::getStoName, SamstoStorage::getStoName);
        //位置
        lambdaQueryWrapper.selectAs(SamstoStorage::getPosition, SamstoStorage::getPosition);
        //父ID
        lambdaQueryWrapper.selectAs(SamstoStorage::getPid, SamstoStorage::getPid);
        //描述
        lambdaQueryWrapper.selectAs(SamstoStorage::getDescribe, SamstoStorage::getDescribe);
        //机构
        lambdaQueryWrapper.selectAs(SamstoStorage::getOrgId, SamstoStorage::getOrgId);
        //状态
        lambdaQueryWrapper.selectAs(SamstoStorage::getStatus, SamstoStorage::getStatus);
        //所属科室
        lambdaQueryWrapper.selectAs(SamstoStorage::getDeptName, SamstoStorage::getDeptName);
        //删除标记
        lambdaQueryWrapper.selectAs(SamstoStorage::getDelFlag, SamstoStorage::getDelFlag);
        //创建人
        lambdaQueryWrapper.selectAs(SamstoStorage::getCreator, SamstoStorage::getCreator);
        //创建时间
        lambdaQueryWrapper.selectAs(SamstoStorage::getCreateTime, SamstoStorage::getCreateTime);
        //修改人
        lambdaQueryWrapper.selectAs(SamstoStorage::getEditor, SamstoStorage::getEditor);
        //修改时间
        lambdaQueryWrapper.selectAs(SamstoStorage::getEditTime, SamstoStorage::getEditTime);
        //删除时间
        lambdaQueryWrapper.selectAs(SamstoStorage::getDelTime, SamstoStorage::getDelTime);
        return lambdaQueryWrapper;
    }

    @Override
    public Result findPageList(SamstoStorageParam pageParam) {
        return this.findListByGId(pageParam);
    }

    @Override
    public Result allList(SamstoStorageParam pageParam) {
        MPJLambdaWrapper<SamstoStorage> queryWrapper = this.initWrapper();
        queryWrapper.selectAs(SysOrgDepartment::getName, SamstoStorageDto::getDeptNameer);
        queryWrapper.leftJoin(SysOrgDepartment.class, SysOrgDepartment::getCode, SamstoFridge::getDeptName);
        if (StringUtils.isNotBlank(pageParam.getDeptName())) {
            queryWrapper.eq(SamstoStorage::getDeptName, pageParam.getDeptName());
        }
        queryWrapper.eq(SamstoStorage::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getKeywords())) {
            queryWrapper.and(wrapper -> wrapper.like(SamstoStorage::getStoName, pageParam.getKeywords())
                    .or().like(SamstoStorage::getPosition, pageParam.getKeywords())
                    .or().like(SamstoStorage::getDescribe, pageParam.getKeywords()));
        }
        queryWrapper.orderByAsc(SamstoStorage::getCreateTime);
        List<SamstoStorageDto> samstoStorageDtos = this.baseMapper.selectJoinList(SamstoStorageDto.class, queryWrapper);
        List<StorageDto> mapList = new ArrayList<>();

        for (SamstoStorageDto eqEquiptType : samstoStorageDtos) {
            String parentId = eqEquiptType.getPid();
            if (StringUtils.isBlank(parentId)) {
                StorageDto storageDto = new StorageDto();
                storageDto.setId(eqEquiptType.getId());
                storageDto.setStoName(eqEquiptType.getStoName());
                storageDto.setDescribe(eqEquiptType.getDescribe());
                storageDto.setPid(eqEquiptType.getPid());
                mapList.add(storageDto);
            }
        }
        for (StorageDto storageDto : mapList) {
            List<StorageDto> child = getChild(storageDto, samstoStorageDtos);
            storageDto.setChildren(child);
        }
        List<StorageDto> storageDtos = mapList.stream().filter(item -> CollectionUtils.isNotEmpty((Collection<?>) item.getChildren())).collect(Collectors.toList());

        //获取仓库的基础信息
        List<SamstoStorageFridgeDto> samstoStorageData = storageFridgeMapper.getSamstoStorageData();
        Map<String, List<SamstoStorageFridgeDto>> stringListMap = samstoStorageData.stream().collect(Collectors.groupingBy(SamstoStorageFridgeDto::getStorageId));
        for (StorageDto storageDto : storageDtos) {
            for (StorageDto childChild : storageDto.getChildren()) {
                List<SamstoStorageFridgeDto> fridgeList = stringListMap.get(childChild.getId());
                if (CollectionUtils.isNotEmpty(fridgeList)) {
                    childChild.setBaseData(fridgeList.get(0));
                }
            }
        }

        return Result.succ(1, "获取信息成功", storageDtos);
    }

    private List<StorageDto> getChild(StorageDto m, List<SamstoStorageDto> eqEquiptTypes) {
        List<StorageDto> result = new ArrayList();
        for (SamstoStorageDto eqEquiptType : eqEquiptTypes) {
            if (StringUtils.isNotBlank(eqEquiptType.getPid()) && eqEquiptType.getPid().equals(m.getId())) {
                StorageDto storageDto1 = new StorageDto();
                storageDto1.setId(eqEquiptType.getId());
                storageDto1.setStoName(eqEquiptType.getStoName());
                storageDto1.setDescribe(eqEquiptType.getDescribe());
                storageDto1.setPid(eqEquiptType.getPid());
                result.add(storageDto1);
            }
        }

        for (StorageDto ma : result) {
            ma.setChildren(getChild(ma, eqEquiptTypes));
        }
        if (result.size() == 0) {
            return null;
        }
        return result;
    }

    @Override
    public Result findListByGId(SamstoStorageParam pageParam) {
        MPJLambdaWrapper<SamstoStorage> queryWrapper = this.initWrapper();
        queryWrapper.selectAs(SysOrgDepartment::getName, SamstoStorageDto::getDeptNameer);
        queryWrapper.leftJoin(SysOrgDepartment.class, SysOrgDepartment::getCode, SamstoFridge::getDeptName);
        Page<SamstoStorageDto> page = new Page<SamstoStorageDto>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        if (StringUtils.isNotBlank(pageParam.getDeptName())) {
            queryWrapper.eq(SamstoStorage::getDeptName, pageParam.getDeptName());
        }
        queryWrapper.eq(SamstoStorage::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getKeywords())) {
            queryWrapper.and(wrapper -> wrapper.like(SamstoStorage::getStoName, pageParam.getKeywords())
                    .or().like(SamstoStorage::getPosition, pageParam.getKeywords())
                    .or().like(SamstoStorage::getDescribe, pageParam.getKeywords()));
        }
        queryWrapper.orderByAsc(SamstoStorage::getCreateTime);
        try {
            SysUser sysUser = RedisUserManager.getUser();
            if (ToolsUtils.isNotEmpty(sysUser)) {
                queryWrapper.eq(SamstoStorage::getOrgId, sysUser.getOrgId());
            }
            page = this.baseMapper.selectJoinPage(page, SamstoStorageDto.class, queryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.succ(1, "获取信息成功", page);
    }

    @Override
    public Result getInfoById(String id) {
        SamstoStorage SamstoStorage = this.baseMapper.selectById(id);
        return Result.succ(1, "获取信息成功", SamstoStorage);
    }

    @Override
    public Result add(SamstoStorageParam param) {
        SamstoStorage info = new SamstoStorage();
        try {
            SysUser sysUser = RedisUserManager.getUser();
            if (ToolsUtils.isNotEmpty(sysUser)) {
                param.setCreator(sysUser.getId());
                param.setOrgId(sysUser.getOrgId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        param.setCreateTime(new Date());
        BeanUtil.copyProperties(param, info);
        info.setDelFlag(0);
        info.setStatus(1);
        this.baseMapper.insert(info);
        return Result.succ(1, "添加信息成功", null);
    }

    @Override
    public Result edit(SamstoStorageParam param) {
        Map returnMap = new HashMap();
        SamstoStorage info = new SamstoStorage();
        try {
            SysUser sysUser = RedisUserManager.getUser();
            if (ToolsUtils.isNotEmpty(sysUser)) {
                param.setEditor(sysUser.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        param.setEditTime(new Date());
        BeanUtil.copyProperties(param, info);
        this.baseMapper.updateById(info);
        returnMap.put("id", param.getId());
        return Result.succ(1, "修改信息成功", returnMap);
    }

    @Override
    public Result delete(List<String> ids) {
        Result result;
        try {
            boolean b = this.removeByIds(ids);
            if (b) {
                result = Result.succ(1, "删除成功", null);
            } else {
                result = Result.fail(400, "删除失败", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail(400, "删除失败", "");
        }
        return result;
    }

    @Override
    public Result updelete(List<String> ids) {
        Result result;
        LambdaUpdateWrapper<SamstoStorage> lambdaUpdateWrapper = new UpdateWrapper<SamstoStorage>().lambda();
        // set 表示要更新的字段， eq 表示  WHERE 条件
        lambdaUpdateWrapper.set(SamstoStorage::getDelFlag, 1)
                .in(SamstoStorage::getId, ids);
        this.baseMapper.update(new SamstoStorage(), lambdaUpdateWrapper);

        try {
            int b = this.baseMapper.update(new SamstoStorage(), lambdaUpdateWrapper);
            if (b > 0) {
                result = Result.succ(1, "删除成功", null);
            } else {
                result = Result.fail(400, "删除失败", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail(400, "删除失败", "");
        }
        return result;
    }

    @Transactional
    @Override
    public Result saveOrUpdateList(SamstoStorageParam param) {
        Result result;
        try {
            SysUser sysUser = RedisUserManager.getUser();
            if (ToolsUtils.isEmpty(sysUser)) {
                return Result.fail(304, "请重新登陆", "");
            }
            for (SamstoStorage info : param.getInfoList()) {
                if (StringUtils.isNotBlank(info.getId())) {
                    info.setEditor(sysUser.getId());
                    info.setEditTime(new Date());
                    this.baseMapper.updateById(info);
                } else {
                    info.setCreator(sysUser.getId());
                    info.setOrgId(sysUser.getOrgId());
                    info.setCreateTime(new Date());
                    info.setDelFlag(0);
                    info.setStatus(1);
                    this.baseMapper.insert(info);
                }
            }
            Boolean b = this.saveOrUpdateBatch(param.getInfoList());
            if (b) {
                result = Result.succ(1, "保存成功", null);
            } else {
                result = Result.fail(400, "保存失败", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail(400, "保存失败", "");
        }
        return result;
    }
}

